package com.sakura.system.service.impl.jrjimpl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sakura.system.coommon.Constants;
import com.sakura.system.coommon.enums.ResultCodeEnum;
import com.sakura.system.coommon.enums.RoleEnum;
import com.sakura.system.dao.jrjdao.User1Mapper;
import com.sakura.system.entity.jrj.Account;
import com.sakura.system.entity.jrj.User1;
import com.sakura.system.exception.CustomException;
import com.sakura.system.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户的业务处理
 **/
@Service
public class User1Service {

    @Resource
    private User1Mapper user1Mapper;

    /**
     * 新增
     */
    public void add(User1 user1) {
        User1 dbuser1 = user1Mapper.selectByUsername(user1.getUsername());
        if (ObjectUtil.isNotNull(dbuser1)) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        if (ObjectUtil.isEmpty(user1.getPassword())) {
            user1.setPassword(Constants.USER_DEFAULT_PASSWORD);
        }
        if (ObjectUtil.isEmpty(user1.getName())) {
            user1.setName(user1.getUsername());
        }
        user1.setRole(RoleEnum.USER.name());
        user1Mapper.insert(user1);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        user1Mapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            user1Mapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(User1 user1) {
        user1Mapper.updateById(user1);
    }

    /**
     * 根据ID查询
     */
    public User1 selectById(Integer id) {
        return user1Mapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<User1> selectAll(User1 user1) {
        return user1Mapper.selectAll(user1);
    }

    /**
     * 分页查询
     */
    public PageInfo<User1> selectPage(User1 user1, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User1> list = user1Mapper.selectAll(user1);
        return PageInfo.of(list);
    }

    public Account login(Account account) {
        Account dbuser1 = user1Mapper.selectByUsername(account.getUsername());
            if (ObjectUtil.isNull(dbuser1)) {
                throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
            }
            if (!account.getPassword().equals(dbuser1.getPassword())) {
                throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
            }
             //生成token
            String tokenDate = dbuser1.getId() + "-" + RoleEnum.USER.name();
            String token = TokenUtils.createToken(tokenDate, dbuser1.getPassword());
            dbuser1.setToken(token);
            return dbuser1;
        }
}